package plgutils

import (
	"dgo/goutils/utils"
	"dgo/plg/plgbase"
	"fmt"
	"gitee.com/ymofen/gobase/golog"
	"gitee.com/ymofen/supervalue"
)

type PlgAppCtrl struct {
	plgbase.PlgBase
}

func (this *PlgAppCtrl) LoadWorkersConf(conf *wrapper.SuperValue) {
	if conf == nil {
		return
	}
	conf.CheckExistsIntFunc("work-max-n", func(val int64) {
		utils.DefaultWorkers().ConfigMaxWork(int32(val))
		golog.Infof("work-max-n:%d", val)
	})

	conf.CheckExistsIntFunc("work-min-n", func(val int64) {
		utils.DefaultWorkers().ConfigMinWork(int32(val))
		golog.Infof("work-min-n:%d", val)
	})
}

/*
	{
	  "id": "app-ctrl",
	  "type": "utils.app.ctrl",
	  "conf": {
	    "workers": {
	      "work-max-n": 128,
	      "work-min-n": 128
	    },
	    "debug-mode": 0
	  }
	},
*/
func (this *PlgAppCtrl) ReloadConf(conf *wrapper.SuperValue) error {
	if conf == nil {
		return nil
	}

	conf.CheckExistsIntFunc("debug-mode", func(val int64) {
		utils.DEBUG_MODE = int(val)
		golog.Infof("debug-mode:%d", utils.DEBUG_MODE)
	})

	this.LoadWorkersConf(conf.ValueByName("workers"))

	return nil
}

func (this *PlgAppCtrl) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {

	}
	return
}

func CreatePlgAppCtrlFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &PlgAppCtrl{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
